const rest = require('restler');
const marketInfo = {hk:{prefix:'hk',index:6},sz:{prefix:'sz',index:3},sh:{prefix:'sh',index:3},other:{prefix:'gb_',index:1}};
module.exports = {
    getRealtimePrice:function (stockCode,callback) {
        if(!stockCode || stockCode.indexOf('.')<=0){
            callback({code:400,message:'invalid stockCode.'});
            return;
        }
        stockCode = stockCode.toLowerCase();
        let dot = stockCode.lastIndexOf('.');
        let market = marketInfo[stockCode.substring(dot+1)] || marketInfo['other'];
        let code = stockCode.substring(0,dot);
        let url = 'http://hq.sinajs.cn/list='+market.prefix+(market.prefix=='hk'?(Array(5).join('0') + code).slice(-5):code);
        let retry = true;
        rest.get(url).on('complete', function(result) {
            if (result instanceof Error) {
                console.log('Error:', result.message);
                if (retry){
                    retry = !retry;
                    this.retry(100);
                }else{
                    callback({'code': 500, 'message': result.message});
                }
            } else {
                let elements = result.split(",");
                callback(null, elements.length>=4?elements[market.index]:null);
            }
        });
    },
    getRealtimeListPrice:function (stockCodes,callback) {
        if(!stockCodes||stockCodes.length ==0)
            callback(null, []);
        var stocks = "",dot = "",market = "" ,code = "";
        var i = 0;
        for(stockCode of stockCodes){
            if(!stockCode || stockCode.indexOf('.')<=0){
                stocks += "*";//无股票代码
                if(i < stockCodes.length -1)
                    stocks += ",";
                i++;
                break;
            }
            stockCode = stockCode.toLowerCase();
            dot = stockCode.lastIndexOf('.');
            market = marketInfo[stockCode.substring(dot+1)] || marketInfo['other'];
            code = stockCode.substring(0,dot);
            stocks += market.prefix+(market.prefix=='hk'?(Array(5).join('0') + code).slice(-5):code);
            if(i < stockCodes.length -1)
                stocks += ",";
            i++;
        }


        let url = 'http://hq.sinajs.cn/list='+stocks;
        let retry = true;
        rest.get(url).on('complete', function(result) {
            if (result instanceof Error) {
                console.log('Error:', result.message);
                if (retry){
                    retry = !retry;
                    this.retry(100);
                }else{
                    callback({'code': 500, 'message': result.message});
                }
            } else {
                let elements = result.replace(/\n/g,"");
                elements = elements.split(";");
                if(elements && elements.length >0)//最后位多余空要删除
                    elements.splice(elements.length-1);
                var prices = [];
                for(element of elements){

                    let price = element.split(",");
                    prices.push(price.length>=4?price[market.index]:"");
                }
                callback(null, prices);
            }
        });
    },
    getRealRate:function (importPrice, stockCode,callback) {
        let that = this;
        that.getRealtimePrice(stockCode,function (err, realtimePrice) {
            callback(err, !err && that.calcRate(importPrice,realtimePrice));
        });
    },
    /**
     * 计算盈利率
     * @param numerator 实际值
     * @param denominator 参考值
     * @returns {*}
     */
    calcRate:function (numerator,denominator) {
        let n = parseFloat(numerator);
        let m = parseFloat(denominator);
        if (isNaN(n) || isNaN(m)|| m ==0){ return '0%'; }
        let rate = (numerator-denominator)*100/denominator;
        return rate.toFixed(2)+'%';
    }
};